package com.springboot.v2.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.springboot.v2.utils.HtmlUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexController {


    private Object getRx() throws IOException {
        File file = ResourceUtils.getFile("classpath:rx.json");
        String strJson = FileUtils.readFileToString(file);
        JSONObject jsonObj = JSON.parseObject(strJson);
        Object result = jsonObj.get("result");
        return result;
    }

    @RequestMapping("/rx")
    public String table(Map<String, Object> map) throws IOException {


        map.put("result", getRx());

        return "table";
    }

    @GetMapping(value = "/")
    public ResponseEntity<?> exportPDF() {
        ResponseEntity<?> response = null;
        try {

            Map<String, Object> mapData = new HashMap<>();
            mapData.put("result", getRx());

            String templateContent = HtmlUtils.getTemplateContent("table.ftl", mapData);
            String fileName = "file_export.pdf";
            response = this.getDownloadResponse(HtmlUtils.html2Pdf(templateContent), fileName);
        } catch (Exception e) {
            System.out.printf(e.getMessage());
            response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return response;
    }

    private ResponseEntity<?> getDownloadResponse(ByteArrayOutputStream byteArrayOutputStream, String fileName) throws UnsupportedEncodingException {

        // 获取文件内容的字节数组
        byte[] fileContent = byteArrayOutputStream.toByteArray();
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName); // 替换为实际的文件名和扩展名
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 创建ResponseEntity对象并返回
        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }


}
